package com.eqdd.yiqidian.ui.gongneng.renshi.meeting;

import android.app.AlertDialog;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.eqdd.yiqidian.MeetingNoticeInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.MeetingNoticeInfoBean;
import com.eqdd.yiqidian.bean.MeetingNoticePersonalBean;
import com.eqdd.yiqidian.bean.MeetingNoticeSignInBean;
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.MyCodeUtil;
import com.eqdd.yiqidian.utils.TimeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;

/**
 * Created by jhj on 18-6-1.
 */

public class MeetingNoticeInfoActivity extends BaseActivity {

    private MeetingNoticeInfoActivityCustom dataBinding;
    private SlimAdapterEx<MeetingNoticePersonalBean> slimAdapterEx;
    private MVCCoolHelper<List<MeetingNoticePersonalBean>> mvcHelper;
    private int pageNum = 0;
    private int noticeId;
    private MeetingNoticeInfoBean meetingNotice;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_meeting_notice_info);
        noticeId = getIntent().getIntExtra(Config.ID, -1);
        if (noticeId == -1) {
            finish();
            ToastUtil.showShort("查看详情失败");
            return;

        }

        initTopTitleBar(View.VISIBLE, "会议通知");
        initTopRightText("会议记录", view -> {
            Bundle bundle = new Bundle();
            bundle.putInt(Config.ID, noticeId);
            startActivity(MeetingRecordListActivity.class,bundle);
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initData() {

        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.addItemDecoration(new DividerLineItemDecoration(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_146, new SlimInjector<MeetingNoticePersonalBean>() {
            @Override
            public void onInject(MeetingNoticePersonalBean data, IViewInjector injector) {
                String status = "";
                if (data.getStatus() == -2) {
                    status = "未签到";
                } else if (data.getStatus() == -1) {
                    status = "迟到";
                } else if (data.getStatus() == 1) {
                    status = "已签到";
                }
                injector.text(R.id.tv_name, data.getUserName())
                        .text(R.id.tv_depart, String.format(Locale.CHINA, "%s-%s", data.getDepName(), data.getPostName()))
                        .text(R.id.tv_status, status);
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener((recyclerView, position, v) -> {
                /*if (position == 0){
                    dataBinding
                }else {
                    int id = slimAdapterEx.getDataItem(position).getId();
                    Bundle bundle = new Bundle();
                    bundle.putInt(Config.ID, id);
                    startActivityForResult(MeetingNoticeInfoActivity.class, bundle, Config.UPDATE);
                }*/
        });

        ModelRx2DataSource<MeetingNoticePersonalBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<HttpResult<List<MeetingNoticePersonalBean>>>post(HttpConfig.BASE_URL + HttpConfig.MEETING_NOTICE_SIGN_IN_INFO)
                        .params("userGuid", user.getGuid())
                        .params("comid", user.getCompanyId())
                        .params("noticeId", noticeId)
                        .params("page", pageNum)
                        .converter(new JsonConverter<HttpResult<List<MeetingNoticePersonalBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(result -> {
                            if (page == 1) {
                                mvcHelper.setAutoLoadMore(true);
                            }
                            pageNum = result.getNextpage();
                            return Flowable.just(result.getItems() == null ? new ArrayList() : result.getItems());
                        });
            }
        }, 10);
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();

        OkGo.<HttpResult<MeetingNoticeInfoBean>>post(HttpConfig.BASE_URL + HttpConfig.MEETING_NOTICE_INFO)
                .params("userGuid", user.getGuid())
                .params("comid", user.getCompanyId())
                .params("noticeId", noticeId)
                .execute(new JsonCallBack<HttpResult<MeetingNoticeInfoBean>>() {
                    @Override
                    public void onSuccess(Response<HttpResult<MeetingNoticeInfoBean>> response) {
                        HttpResult result = response.body();
                        if (result.getStatus() == 200) {
                            meetingNotice = (MeetingNoticeInfoBean) result.getItems();
                            dataBinding.tvType.setText(meetingNotice.getType());
                            dataBinding.tvPerson.setText(String.format(Locale.CHINA, "主持人：%s", meetingNotice.getCompere().getRealName()));
                            dataBinding.tvPosition.setText(String.format(Locale.CHINA, "地   点：%s", meetingNotice.getPlace()));
                            dataBinding.tvTime.setText(String.format(Locale.CHINA, "时   间：%s 至 %s",
                                    TimeUtil.formatWebTime(meetingNotice.getStartTime()), TimeUtil.formatWebTime(meetingNotice.getEndTime())));
                            dataBinding.layoutHead.removeAllViews();
                            dataBinding.layout.setVisibility(View.VISIBLE);
                            if (meetingNotice.getCompere().getGuid().equals(user.getGuid())) {
                                if (meetingNotice.getStatus() == 0) {
                                    dataBinding.tvStatus.setText("发起签到");
                                    dataBinding.tvStatus.setOnClickListener(v -> {
                                        startSignIn();
                                    });

                                } else if (meetingNotice.getStatus() == 1) {
                                    dataBinding.tvStatus.setText("开始签到");
                                    dataBinding.tvStatus.setOnClickListener(v -> {
                                        showER();
                                    });
                                } else if (meetingNotice.getStatus() == 2) {
                                    dataBinding.tvStatus.setOnClickListener(v -> {
                                        ToastUtil.showShort("签到结束");
                                    });
                                    dataBinding.tvStatus.setTextColor(Color.BLACK);
                                    dataBinding.tvStatus.setText("签到结束");
                                    dataBinding.tvStatus.setBackgroundResource(R.drawable.btn_cancel);
                                }
                            } else {
                                dataBinding.tvStatus.setVisibility(View.GONE);
                            }

                            slimAdapterEx.addHeader(dataBinding.layout);
                        }
                    }
                });
    }

    public void startSignIn() {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.MEETING_NOTICE_SIGN_IN_LLUNCH)
                .params("userGuid", user.getGuid())
                .params("comid", user.getCompanyId())
                .params("noticeId", noticeId)
                .execute(new JsonCallBack<HttpResult>() {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult result = response.body();
                        if (result.getStatus() == 200) {
                            showER();
                            dataBinding.tvStatus.setText("开始签到");
                        } else if (result.getStatus() == 206) {
                            showER();
                        }
                    }
                });
    }


    public void showER() {
        if (meetingNotice == null) {
            ToastUtil.showShort("二维码生成失败");
            return;
        }
        MeetingNoticeSignInBean bean = new MeetingNoticeSignInBean();
        MeetingNoticeSignInBean.ItemBean itemBean = new MeetingNoticeSignInBean.ItemBean();
        bean.setType(4);
        bean.setUgid("");
        bean.setName("");
        itemBean.setId(meetingNotice.getId());
        itemBean.setType(meetingNotice.getType());
        itemBean.setPlace(meetingNotice.getPlace());
        itemBean.setStartTime(meetingNotice.getStartTime());
        itemBean.setEndTime(meetingNotice.getEndTime());
        bean.setData(itemBean);
        String s = new Gson().toJson(bean, MeetingNoticeSignInBean.class);
        MyCodeUtil.createImage(s, 400, new MyCodeUtil.OnEncodeQRCodeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap bitmap) {
                View view = LayoutInflater.from(MeetingNoticeInfoActivity.this).inflate(R.layout.layout_image_view, null);
                ((ImageView) view.findViewById(R.id.image_view)).setImageBitmap(bitmap);
                new AlertDialog.Builder(MeetingNoticeInfoActivity.this)
                        .setView(view)
                        .create()
                        .show();
            }

            @Override
            public void onAnalyzeFailed() {

                System.out.println();
            }
        });

    }

    @Override
    public void setView() {


    }

}
